package com.example.guardian.client.spring.provider;

import com.alibaba.dubbo.common.json.JSON;
import com.example.guardian.client.message.model.MessageModel;
import com.example.guardian.client.proxy.InvokerHolder;
import com.example.guardian.client.util.ActionContextUtil;
import org.springframework.aop.MethodBeforeAdvice;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 事务消息初始化拦截器
 *
 * @author gang.wang 2021/12/9
 */
public class TransactionProviderPreInterceptor implements MethodBeforeAdvice {

    @Override
    public void before(Method method, Object[] args, Object target) throws Throwable {
        TransactionProvider transactionProvider = method.getAnnotation(TransactionProvider.class);
        if (transactionProvider != null) {
            MessageModel messageModel = new MessageModel();
            messageModel.setBizType(transactionProvider.bizType());
            messageModel.setSourceApp(transactionProvider.sourceApp());
            // 暂定雪花算法

            Map<String, Object> context = ActionContextUtil.fetchActionRequestContext(method, args);
            messageModel.setMessageId(context.get("messageId").toString());
            String contextStr = JSON.json(context);
            messageModel.setJsonMessageInfo(contextStr);
            InvokerHolder.get().preTransaction();
        }
    }
}
